$(function() {
	var date = new Date();
	var year = dateFormat("YYYY", date);
	newStaticMaps(year,"");
})
/**
 * 按年、月查询
 */
function selectByYearOrMonth(){
	var years = $("#years").val();
	var months = $("#months").val();
	newStaticMaps(years,months);
}
/**
 * 清空查询条件
 */
function reloadYearOrMonth(){
	// $("#yearandmonth").html("");
	// var date = new Date();
	// var year = dateFormat("YYYY", date);
	// newStaticMaps(year,"");
	location.reload();
}
/**
 * 查询费用排行，并存入全局对象
 */
function newStaticMaps(years,months){
	$.ajax({
		url: 'http://localhost:9000/statistical/freightrank/businessincome-chart?year='+years+'&month='+months,
		type: 'get',
		dataType: 'json',
		success: function(map) {
			staticMaps=map;
			var yearandmonth ="";
			if(years!=null && years!=""){
				yearandmonth+=years+"年";
			}
			if(months!=null && months!=""){
				yearandmonth+=months+"月";
			}
			$("#yearandmonth").html(yearandmonth);

			businessIncomes = staticMaps.businessIncomes;
			
			factDealDates = new Array(); //结算时间 月份
			// reduceFunds = new Array();    //减款
			// payKickbacks = new Array();    //付回扣
			// moneyOfChangePays = new Array();    //代收货款变更后金额
			carryGoodsFees = new Array();    //送货费
			carriages = new Array();    //运费
			insurances = new Array();    //保险费
			sumMoney = new Array();
			for (var i = 0; i < businessIncomes.length; i++) {
				var businessIncome = businessIncomes[i];
				var date = businessIncome.factDealDate;
				if(date!=null && date!=""){
					factDealDates.push(date.substring(date.indexOf('-')+1,date.indexOf('-',date.indexOf('-')+1))+'月');
					// reduceFunds.push(businessIncome.reduceFund);    //减款
					// payKickbacks.push(businessIncome.payKickback);   //付回扣
					// moneyOfChangePays.push(businessIncome.moneyOfChangePay);    //代收货款变更后金额
					carryGoodsFees.push(businessIncome.carryGoodsFee);
					carriages.push(businessIncome.carriage);
					insurances.push(businessIncome.insurance);
					sumMoney.push(businessIncome.carryGoodsFee+businessIncome.carriage+businessIncome.insurance);
				}
				
			}
			
			chartOne();
		}
	})
}
/**
 * @param {Object} map
 * 图表结构
 */
function chartOne() {
	// 基于准备好的dom，初始化echarts实例
	var myChart = echarts.init(document.getElementById('main'));
	// app.title = '堆叠柱状图';
	option = {
	    tooltip : {
	        trigger: 'axis',
	        axisPointer : {            // 坐标轴指示器，坐标轴触发有效
	            type : 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
	        }
	    },
	    legend: {
	        data:['送货费','运费','保险费','合计']
	    },
	    grid: {
	        left: '3%',
	        right: '4%',
	        bottom: '3%',
	        containLabel: true
	    },
	    xAxis : [
	        {
	            type : 'category',
				data : factDealDates
	            // data : ['一月','二月','三月','四月','五月','六月','七月','八月','九月','十月','十一月','十二月']
	        }
	    ],
	    yAxis : [
	        {
	            type : 'value'
	        }
	    ],
	    series : [
	        {
	            name:'送货费',
	            type:'bar',
				stack: '营业收入',
				data : carryGoodsFees
	            // data:[320, 332, 301, 334, 390,320, 332, 301, 334, 390,443,445]
	        },
	        {
	            name:'运费',
	            type:'bar',
	            stack: '营业收入',
	            data:carriages
				 // data:[320, 332, 301, 334, 390,320, 332, 301, 334, 390,443,445]
	        },
	        {
	            name:'保险费',
	            type:'bar',
				stack: '营业收入',
	            data:insurances,
				 // data:[30, 332, 01, 334, 390,320, 332, 301, 334, 390,443,445]
	        },
			
			{
			    name:'合计',
			    type:'bar',
				stack: '合计',
			    data:sumMoney,
				 // data:[30, 332, 01, 334, 390,320, 332, 301, 334, 390,443,445]
			}
	    ]
	};

	// 使用刚指定的配置项和数据显示图表。
	myChart.setOption(option,true);
}

/**
 * 合计
 */
function chartTwo() {
	var totalCarryGoodsFees=0;
	var totalCarriages=0;
	var totalInsurances=0;
	for (var i = 0; i < carryGoodsFees.length; i++) {
		totalCarryGoodsFees+=carryGoodsFees[i];//送货费
	}
	for (var i = 0; i < carriages.length; i++) {
		totalCarriages+=carriages[i];//运费
	}
	for (var i = 0; i < insurances.length; i++) {
		totalInsurances+=insurances[i];//保险费
	}
	
	// 基于准备好的dom，初始化echarts实例
	var myChart = echarts.init(document.getElementById('main'));
	
	option = {
	    tooltip: {
	        trigger: 'item',
	        formatter: "{a} <br/>{b}: {c} ({d}%)"
	    },
	    legend: {
	        orient: 'vertical',
	        x: 'left',
	        data:['送货费','运费','保险费']
	    },
	    series: [
	        {
	            name:'收入来源',
	            type:'pie',
	            selectedMode: 'single',
	            radius: [0, '30%'],
	
	            label: {
	                normal: {
	                    position: 'inner'
	                }
	            },
	            labelLine: {
	                normal: {
	                    show: false
	                }
	            },
	            data:[
	                {value:totalCarriages+totalCarryGoodsFees, name:'运输', selected:true},
	                {value:totalInsurances, name:'保险'}
	            ]
	        },
	        {
	            name:'收入来源',
	            type:'pie',
	            radius: ['40%', '55%'],
	            label: {
	                normal: {
	                    formatter: '{a|{a}}{abg|}\n{hr|}\n  {b|{b}：}{c}  {per|{d}%}  ',
	                    backgroundColor: '#eee',
	                    borderColor: '#aaa',
	                    borderWidth: 1,
	                    borderRadius: 4,
	                    // shadowBlur:3,
	                    // shadowOffsetX: 2,
	                    // shadowOffsetY: 2,
	                    // shadowColor: '#999',
	                    // padding: [0, 7],
	                    rich: {
	                        a: {
	                            color: '#999',
	                            lineHeight: 22,
	                            align: 'center'
	                        },
	                        // abg: {
	                        //     backgroundColor: '#333',
	                        //     width: '100%',
	                        //     align: 'right',
	                        //     height: 22,
	                        //     borderRadius: [4, 4, 0, 0]
	                        // },
	                        hr: {
	                            borderColor: '#aaa',
	                            width: '100%',
	                            borderWidth: 0.5,
	                            height: 0
	                        },
	                        b: {
	                            fontSize: 16,
	                            lineHeight: 33
	                        },
	                        per: {
	                            color: '#eee',
	                            backgroundColor: '#334455',
	                            padding: [2, 4],
	                            borderRadius: 2
	                        }
	                    }
	                }
	            },
	            // data:[
	            //     {value:335, name:'直达'},
	            //     {value:310, name:'邮件营销'},
	            //     {value:234, name:'联盟广告'},
	            //     {value:135, name:'视频广告'},
	            //     {value:1048, name:'百度'},
	            //     {value:251, name:'谷歌'},
	            //     {value:147, name:'必应'},
	            //     {value:102, name:'其他'}
	            // ]
				data:[
				    {value:totalCarriages, name:'运费'},
				    {value:totalCarryGoodsFees, name:'送货费'},
					{value:totalInsurances, name:'保险费'}
				]
	        }
	    ]
	};
	// 使用刚指定的配置项和数据显示图表。
	myChart.setOption(option,true);
}

	
/**
 * 
 */
function chartFour() {
	// 基于准备好的dom，初始化echarts实例
	var myChart = echarts.init(document.getElementById('main'));
	option = {
	    title : {
	        text: '营业收入',
	        // subtext: '纯属虚构'
	    },
	    tooltip : {
	        trigger: 'axis'
	    },
	    legend: {
	        data:['运费','送货费','保险费']
	    },
	    toolbox: {
	        show : true,
	        feature : {
	            dataView : {show: false, readOnly: false},
	            magicType : {show: true, type: ['line', 'bar']},
	            restore : {show: true},
	            saveAsImage : {show: true}
	        }
	    },
	    calculable : true,
	    xAxis : [
	        {
	            type : 'category',
	            // data : ['1月','2月','3月','4月','5月','6月','7月','8月','9月','10月','11月','12月']
				data : factDealDates
	        }
	    ],
	    yAxis : [
	        {
	            type : 'value'
	        }
	    ],
		
	    series : [
	        {
	            name:'送货费',
	            type:'bar',
	            data:carryGoodsFees,
	            markPoint : {
	                data : [
	                    {type : 'max', name: '最大值'},
	                    {type : 'min', name: '最小值'}
	                ]
	            },
	            markLine : {
	                data : [
	                    {type : 'average', name: '平均值'}
	                ]
	            }
	        },
	        {
	            name:'运费',
	            type:'bar',
	            data:carriages,
	           markPoint : {
	               data : [
	                   {type : 'max', name: '最大值'},
	                   {type : 'min', name: '最小值'}
	               ]
	           },
	           markLine : {
	               data : [
	                   {type : 'average', name: '平均值'}
	               ]
	           }
	        },
	        {
	            name:'保险费',
	            type:'bar',
	            data:insurances,
	            markPoint : {
	                data : [
	                    {type : 'max', name: '最大值'},
	                    {type : 'min', name: '最小值'}
	                ]
	            },
	            markLine : {
	                data : [
	                    {type : 'average', name: '平均值'}
	                ]
	            }
	        }
	    ]
	};
	// 使用刚指定的配置项和数据显示图表。
	myChart.setOption(option,true);
}


function dateFormat(fmt, date) {
    var ret;
	var opt = {
        "Y+": date.getFullYear().toString(),        // 年
        "m+": (date.getMonth() + 1).toString(),     // 月
        "d+": date.getDate().toString(),            // 日
        "H+": date.getHours().toString(),           // 时
        "M+": date.getMinutes().toString(),         // 分
        "S+": date.getSeconds().toString()          // 秒
        // 有其他格式化字符需求可以继续添加，必须转化成字符串
    };
    for (var k in opt) {
        ret = new RegExp("(" + k + ")").exec(fmt);
        if (ret) {
            fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
        };
    };
    return fmt;
}